from fastapi import FastAPI, Request, HTTPException
import subprocess
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# 配置 - 请修改为你的实际信息
# 注意：这里使用的是Gitee的WebHook密码（对应x-gitee-token）
WEBHOOK_PASSWORD = "123456789"  # 与Gitee上设置的"WebHook密码"一致
DEPLOY_SCRIPT_PATH = "/home/aps/ai/mobile-ai-app/T.sh"  # 部署脚本路径


def verify_token(token: str) -> bool:
    """验证WebHook密码（x-gitee-token）"""
    if not token:
        logger.warning("x-gitee-token头为空")
        return False

    # 直接比对密码（WebHook密码方式）
    return token == WEBHOOK_PASSWORD


def run_deploy_script():
    """执行部署脚本"""
    if not os.path.exists(DEPLOY_SCRIPT_PATH):
        error_msg = f"部署脚本不存在: {DEPLOY_SCRIPT_PATH}"
        logger.error(error_msg)
        return error_msg, False

    try:
        os.chmod(DEPLOY_SCRIPT_PATH, 0o755)  # 确保脚本可执行
        result = subprocess.run(
            ["bash", DEPLOY_SCRIPT_PATH],
            capture_output=True,
            text=True,
            timeout=300
        )

        if result.returncode != 0:
            error_msg = f"脚本执行失败: {result.stderr}"
            logger.error(error_msg)
            return error_msg, False

        logger.info(f"脚本执行成功: {result.stdout}")
        return f"部署成功: {result.stdout}", True

    except Exception as e:
        error_msg = f"部署失败: {str(e)}"
        logger.error(error_msg)
        return error_msg, False


@app.post("/webhook")
async def handle_webhook(request: Request):
    try:
        headers = dict(request.headers)
        logger.info(f"请求头: {headers}")

        # 获取Gitee发送的密码（WebHook密码方式）
        token = headers.get("x-gitee-token", "")
        # 获取事件类型（从x-gitee-event或x-git-oschina-event头中获取）
        event_type = headers.get("x-gitee-event") or headers.get("x-git-oschina-event", "unknown")

        # 验证密码
        if not verify_token(token):
            raise HTTPException(status_code=403, detail="x-gitee-token验证失败")

        # 处理推送事件（Push Hook）
        if event_type == "Push Hook":
            message, success = run_deploy_script()
            return {"status": "success" if success else "failed", "message": message}

        logger.info(f"忽略事件类型: {event_type}")
        return {"status": "ignored", "message": f"不处理{event_type}事件"}

    except HTTPException:
        raise
    except Exception as e:
        error_msg = f"处理请求出错: {str(e)}"
        logger.error(error_msg)
        raise HTTPException(status_code=400, detail=error_msg)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5001, log_level="info")
